package matrixCalculator;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.util.Vector;


/**
 * In this class the connection is answered and the message is parsed, The matrixOperation Object is generated
 * so the IO Thread consumes it 
 * **/
class ConnectionThread extends Thread {
	private Vector<MatrixOperation> MatrixOperationBuffer = new Vector<MatrixOperation>();
	private Vector<MatrixOperation> MatrixResultsBuffer = new Vector<MatrixOperation>();
	DataInputStream in;
	DataOutputStream out;
	Socket clientSocket;

	public ConnectionThread (Socket aClientSocket,Vector<MatrixOperation> MatrixOperationsBuffer, Vector<MatrixOperation> MatrixResultsBuffer) {
		try {
			clientSocket = aClientSocket;
			in = new DataInputStream( clientSocket.getInputStream());
			out =new DataOutputStream( clientSocket.getOutputStream());
			this.MatrixOperationBuffer=MatrixOperationsBuffer;
			this.MatrixResultsBuffer=MatrixResultsBuffer;
		} catch(IOException e) {System.out.println("Connection:"+e.getMessage());}
	}
	public void run(){
		try {			                 
			String data="";
			while (true){
				data = in.readUTF();	 // read a line of data from the stream
				System.out.println("Answering");				
				//parse matrix size and operation
				MatrixOperation petition = parseMessage(data, out);				
				MatrixOperationBuffer.add(petition);
			}
			
		}catch (EOFException e){System.out.println("EOF:"+e.getMessage());
		} catch(IOException e) {System.out.println("readline:"+e.getMessage());
		} finally{ try {clientSocket.close();}catch (IOException e){/*close failed*/}}
		

	}
	
	public MatrixOperation parseMessage(String request, DataOutputStream out) {
		MatrixOperation operation= new MatrixOperation();
		String [] arrayAux= request.split("_");
		int N=2;
		String Operator="+";
		if(arrayAux[0]!= null) N=Integer.parseInt(arrayAux[0]);
		if(arrayAux[1]!= null) Operator=arrayAux[1];
		operation.setOperator(Operator);
		operation.setN(N);
		operation.setOut(out);
		
		return operation;
	}
}